<?php
declare(strict_types=1);

namespace Modules\Web\Service;

use HiCommon\Repository\GoodsImgRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\GoodsCateRepository;
use HiCommon\Repository\GoodsSpecsCateRepository;
use HiCommon\Repository\GoodsSpecsRepository;
use HiCommon\Repository\RepairstoreGoodsImgRepository;
use HiCommon\Repository\RepairstoreTypeRepository;
use HiCommon\Repository\RepairstoreGoodsRepository;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\UsersAppriseRepository;
use Modules\Admin\Service\ActivityService;


class GoodsService extends BaseService
{

    /**
     * 商品分类列表
     * yang 20191029
     */
    public function get_goods_cate()
    {
        $where = ['pid' => 0, 'status' => 1];
        $list = GoodsCateRepository::get_cate_list((array)$where);

        $data = ['commonly' => [], 'integral' => []];
        foreach ($list as $key => $value) {
            if ($value['type'] == 1) {
                $data['commonly'][] = $value;
            } else {
                $data['integral'][] = $value;
            }

        }
        return hello_success('ok', $data);
    }

    /**
     * 获取商品规格分类列表
     * yang 2019 11 07
     */
    public function get_specs_cate_list()
    {
        $where = ['repairstore_id' => get_web_shop_id(), 'status' => 1];

        $list = GoodsSpecsCateRepository::get_specs_cate_list($where);

        return hello_success('ok', $list);
    }

    /**
     *    商品列表
     * yang 20191029
     */
    public function get_goods_list(array $arrInput)
    {
        try {
            //获取门店id
            $shop_id = get_web_shop_id();
            $type = intval($arrInput['type']); //商品类型积分商品或普通商品

            $array_where = ['repairstore_id' => $shop_id, 'status' => 1, 'type' => $type];
            $cate_array = GoodsRepository::get_cate_list($array_where);//该门店商品分类列表

            $list = array();
            $field = ['id', 'pic_url', 'name', 'title', 'price', 'integral'];
            foreach ($cate_array as $key => $value) {
                $where = ['cate_id' => $value['cate_id'], 'type' => $type];
                $info = GoodsRepository::get_list_where_limit((array)$where, 3, $field)->toarray();

                $goods = array();
                foreach ($info as $k => $v) {
                    $goods[] = [
                        'id' => $v['id'],
                        'name' => $v['name'],
                        'title' => $v['title'],
                        'pic' => $v['pic_url']['full_src'],
                        'price' => $v['price'],
                        'integral' => reset($v['product_info'])['integral'],
                    ];
                }

                $list[$key]['cate_id'] = $value['cate_id'];
                $list[$key]['cate_name'] = $value['cate']['name'];
                $list[$key]['goods_list'] = $goods;
            }

            return hello_success('ok', $list);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *    获取该门店的所有商品
     *    yang 20191029
     **/
    public function get_goods_all(array $arrInput)
    {
        try {
            //积分商品或普通商品
            if ($arrInput['type']) {
                $arr_where['where']['type'] = $arrInput['type'];
            }
            //分类id
            if ($arrInput['cate_id']) {
                $arr_where['where']['cate_id'] = $arrInput['cate_id'];
            }
            //上下架
            if ($arrInput['status']) {
                $arr_where['where']['status'] = $arrInput['status'];
            }
            $arr_where['where']['repairstore_id'] = get_web_shop_id();

            $arr_where['field'] = ['id', 'name', 'title', 'pic_url', 'price', 'integral', 'status'];
            $arr_where['with'] = ['product_info'];

            $res = GoodsRepository::get_list((array)$arr_where)->toArray();

            $goods = array();
            foreach ($res['data'] as $k => $val) {
                $goods[] = [
                    'id' => $val['id'],
                    'name' => $val['name'],
                    'title' => $val['title'],
                    'pic' => $val['pic_url']['full_src'],
                    'stock' => array_sum(array_column($val['product_info'], 'stock')),
                    'price' => $val['price'],
                    'integral' => reset($val['product_info'])['integral'],
                    'status' => $val['status'],
                ];
            }

            $temp['goods_list'] = $goods;
            $temp['page'] = [
                "current_page" => $res['current_page'],
                "per_page" => $res['per_page'],
                "last_page" => $res['last_page'],
                "total" => $res['total']
            ];

            return hello_success('ok', $temp);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *    获取指定商品详情
     *    yang 20191029
     **/
    public function get_goods_info(int $nId)
    {
        try {
            if (empty($nId)) {
                return hello_error('参数不能为空');
            }
            //获取商品的主表信息
            $arr_option['with'] = ['product', 'img'];
            $res = GoodsRepository::get_one((int)$nId, (array)$arr_option)->toArray();

            $info['goods'] = [
                'id' => $res['id'],
                'shop_id' => $res['repairstore_id'],
                'type' => $res['type'],
                'name' => $res['name'],
                'title' => $res['title'],
                'goods_pic' => $res['pic_url'],
                'cate_id' => $res['cate_id'],
                'price' => $res['price'],
                'price_indication' => $res['price_indication'],
                'integral' => $res['integral'],
                'detail' => $res['detail'],
                'sale' => $res['sale'],
                'status' => $res['status'],
            ];
            $product = [];
            foreach ($res['product'] as $key => $val) {
                $product[] = [
                    'id' => $val['id'],
                    'specs_id' => $val['goods_specs_id'],
                    'name' => $val['specs']['name'],
                    'price' => $val['price'],
                    'integral' => $val['integral'],
                    'stock' => $val['stock'],
                    'pic' => $val['pic'],
                    'id' => $val['id'],
                ];
            }
            $img = [];
            foreach ($res['img'] as $k => $v) {
                $img[] = [
                    'id' => $v['id'],
                    'picurl' => $v['picurl']
                ];
            }
            $info['product_cate_id'] = reset($res['product'])['specs']['goods_specs_cate_id'];
            $info['product'] = $product;
            $info['img'] = $img;

            return hello_success('ok', $info);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 表单数据验证
     */
    public function check_input($data)
    {
        $goods = $data['goods'];
        if (empty($goods['type'])) {
            return ['state' => 1, 'msg' => '商品类型不能为空'];
        }
        if (empty($goods['name'])) {
            return ['state' => 1, 'msg' => '商品名称不能为空'];
        }
        if (empty($goods['title'])) {
            return ['state' => 1, 'msg' => '商品副标题不能为空'];
        }
        if (empty($goods['pic_url'])) {
            return ['state' => 1, 'msg' => '商品封面图不能为空'];
        }
        if (empty($goods['cate_id'])) {
            return ['state' => 1, 'msg' => '商品分类id不能为空'];
        }
        if (empty($goods['price'])) {
            return ['state' => 1, 'msg' => '商品展示价格不能为空'];
        }
        if (empty($goods['price_indication'])) {
            return ['state' => 1, 'msg' => '商品价格说明不能为空'];
        }
        if (empty($goods['detail'])) {
            return ['state' => 1, 'msg' => '商品详情不能为空'];
        }
        if (empty($goods['sale'])) {
            return ['state' => 1, 'msg' => '售后不能为空'];
        }
        if (empty($goods['status'])) {
            return ['state' => 1, 'msg' => '是否上架不能为空'];
        }
        if (empty($data['specs_cate_id'])) {
            return ['state' => 1, 'msg' => '规格分类id不能为空'];
        }
        foreach ($data['product'] as $val) {
            if (empty($val['name'])) {
                return ['state' => 1, 'msg' => '规格属性名称不能有空'];
            }
            if (empty($val['price']) && $goods['type'] == 1) {
                return ['state' => 1, 'msg' => '规格对应的价格不能有空'];
            }
            if (empty($val['integral']) && $goods['type'] == 2) {
                return ['state' => 1, 'msg' => '规格对应的积分不能有空'];
            }
            if (empty($val['stock'])) {
                return ['state' => 1, 'msg' => '规格对应库存不能有空'];
            }
            if (empty($val['pic'])) {
                return ['state' => 1, 'msg' => '规格对应图片不能有空'];
            }
        }
        $img = hi_array_del_null($data['img']);
        if (empty($img)) {
            return ['state' => 1, 'msg' => '图片详情不能为空'];
        }
    }

    /**
     * 添加商品
     * 2019 10 30
     */
    public function add_goods(array $data)
    {
        try {
            $data['goods']['repairstore_id'] = get_web_shop_id();//门店id

            $check = self::check_input($data);
            if ($check['state'] == 1) {
                return hello_error($check['msg']);
            }
            //去除空数据
            $goods = hi_array_del_null($data['goods']);
            $res = GoodsRepository::add_one($goods)->toarray();

            if (!empty($res)) {
                $goods_id = $res['id'];
                if ($data['product']) {
                    self::add_goods_product($goods_id, hi_array_del_null($data['product']), $data['specs_cate_id']);
                }

                if ($data['img']) {
                    self::add_goods_img($goods_id, hi_array_del_null($data['img']));
                }

                return hello_success('添加成功');
            }

            return hello_error('添加失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 插入商品规格属性
     */
    public function add_goods_product($goods_id, $product_array, $specs_cate_id)
    {
        foreach ($product_array as $key => $value) {
            $specs['goods_specs_cate_id'] = $specs_cate_id;
            $specs['name'] = $value['name'];
            $detal = GoodsSpecsRepository::add_one($specs);

            if ($detal) {
                $product['goods_id'] = $goods_id;
                $product['goods_specs_id'] = $detal->id;
                $product['price'] = $value['price'];
                $product['integral'] = $value['integral'];
                $product['stock'] = $value['stock'];
                $product['pic'] = $value['pic'];
                GoodsProductRepository::add_one($product);
            }
        }

    }

    /**
     * 插入商品图片
     */
    public function add_goods_img($goods_id, $imgArray)
    {
        //批量插入商品图片
        $data = array();
        $time = date('Y-m-d H:i:s', time());
        foreach ($imgArray as $key => $value) {
            $data[$key]['goods_id'] = $goods_id;
            $data[$key]['picurl'] = $value;
            $data[$key]['sort'] = $key + 1;
            $data[$key]['created_at'] = $time;
            $data[$key]['updated_at'] = $time;
        }

        return GoodsImgRepository::add_more($data);
    }

    /**
     * 编辑商品
     * 2019 10 30
     */
    public function edit_goods(array $data)
    {
        try {
            $check = self::check_input($data);
            if ($check['state'] == 1) {
                return $check;
            }
            if (empty($data['goods']['id'])) {
                return hello_error('商品id不能为空');
            }

            //去除空数据
            $goods = hi_array_del_null($data['goods']);
            GoodsRepository::edit_one($goods);

            //编辑规格属性
            self::edit_goods_product($data);

            //编辑详情图
            GoodsImgRepository::delete_by_where(['goods_id' => $goods['id']]);

            self::add_goods_img($goods['id'], hi_array_del_null($data['img']));

            return hello_success('编辑成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 编辑规格属性
     */
    public function edit_goods_product($data = [])
    {
        foreach ($data['product'] as $key => $value) {
            $specs_id = $value['specs_id'] ?? 0;
            $specs['goods_specs_cate_id'] = $data['specs_cate_id'];
            $specs['name'] = $value['name'];
            $res = GoodsSpecsRepository::edit_or_create(['id' => $specs_id], $specs);

            $product_id = $value['id'] ?? 0;
            $product['goods_id'] = $data['goods']['id'];
            $product['goods_specs_id'] = $res->id;
            $product['price'] = $value['price'];
            $product['integral'] = $value['integral'];
            $product['stock'] = $value['stock'];
            $product['pic'] = $value['pic'];
            GoodsProductRepository::edit_or_create(['id' => $product_id], $product);
        }
    }

    /**
     * 删除商品规格属性
     * 2019 11 07
     */
    public function del_goods_product(int $pid)
    {
        try {
            if (empty($pid)) {
                return hello_error('规格属性id不能为空');
            }

            GoodsProductRepository::delete_one($pid);

            return hello_success('删除成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 商品上下架
     * 2019 10 30
     */
    public function change_status(array $data)
    {
        try {
            $map = $data['gid'];
            if (!empty($data['status'])) {
                $updata['status'] = $data['status'];
            }
            if (!empty($data['cate_id'])) {
                $updata['cate_id'] = $data['cate_id'];
            }

            GoodsRepository::change_status((array)$map, (array)$updata);

            return hello_success('设置成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除指定商品
     * 2019 10 30
     */
    public function del_goods(array $data)
    {
        try {
            $id_array = hi_array_del_null($data['id']);

            if (empty($id_array)) {
                return hello_error('商品id不能为空');
            }

            //检测商品是否可以删除
            foreach ($id_array as $item) {
                $result = ActivityService::goods_is_del((int)$item);
                if ($result['state'] != 0) {
                    return hello_error($result['msg']);
                }
            }

            GoodsRepository::delete_more($id_array);

            return hello_success('删除成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /*****************************************服务商品**************************************************/

    /**
     * 商品分类列表
     * yang 2019 10 30
     */
    public function get_repair_type()
    {
        try {
            $res = RepairstoreTypeRepository::get_all(['status' => 1], ['id', 'title']);

            return hello_success('ok', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 服务商品列表
     * yang 2019 10 30
     */
    public function get_repair_list(array $data)
    {
        try {
            $shop_id = get_web_shop_id();//门店id
            $data['shop_id'] = $shop_id;

            $res = RepairstoreGoodsRepository::api_get_list($data)->toArray();

            $goods = array();
            foreach ($res['data'] as $k => $val) {
                $goods[] = [
                    'id' => $val['id'],
                    'name' => $val['name'],
                    'pic' => reset($val['pic'])['picurl']['full_src'],
                    'price' => $val['price'],
                    'address' => $val['shop']['address'],
                    'type' => $val['type'],
                    'status' => $val['status'],
                ];
            }

            $temp['goods_list'] = $goods;
            $temp['page'] = [
                "current_page" => $res['current_page'],
                "per_page" => $res['per_page'],
                "last_page" => $res['last_page'],
                "total" => $res['total']
            ];

            return hello_success('ok', $temp);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 表单提交的数据验证
     */
    public function data_validation($data)
    {
        $goods = $data['goods'];
        if (empty($goods['type'])) {
            return ['state' => 1, 'msg' => '商品类型不能为空'];
        }
        if (empty($goods['name'])) {
            return ['state' => 1, 'msg' => '商品名称不能为空'];
        }
        if (empty($goods['price'])) {
            return ['state' => 1, 'msg' => '价格不能为空'];
        }
        if (empty($goods['price_indication'])) {
            return ['state' => 1, 'msg' => '价格说明不能为空'];
        }
        if (empty($goods['status'])) {
            return ['state' => 1, 'msg' => '是否上下架不能为空'];
        }
        if (empty($goods['detail'])) {
            return ['state' => 1, 'msg' => '商品详情不能为空'];
        }
        if (empty($goods['fuwu'])) {
            return ['state' => 1, 'msg' => '售后服务不能为空'];
        }
        if (empty(hi_array_del_null($data['pic']))) {
            return ['state' => 1, 'msg' => '服务商品图片不能为空'];
        }
    }

    /**
     * 添加服务商品
     * yang 2019 10 30
     */
    public function add_repair_goods(array $data)
    {
        try {
            $shop_id = get_web_shop_id();//门店id

            $check = self::data_validation($data);
            if ($check['state'] == 1) {
                return hello_error($check['msg']);
            }
            //去除空数据
            $data = hi_array_del_null($data);

            $map = ['id' => $shop_id];
            $arr_option['field'] = ['id', 'longitude', 'latitude'];
            $repair = ShopRepository::get_one_by_where($map, $arr_option);

            if ($repair) {
                $data['goods']['repairstore_id'] = $shop_id;
                $data['goods']['longitude'] = $repair->longitude;
                $data['goods']['latitude'] = $repair->latitude;
            } else {
                return hello_error('门店不存在');
            }

            $res = RepairstoreGoodsRepository::add_one($data['goods'])->toarray();

            $imgs = hi_array_del_null($data['pic']);

            $imgArray = array();
            foreach ($imgs as $key => $value) {
                $imgArray['goods_id'] = $res['id'];
                $imgArray['picurl'] = $value;
                $imgArray['sorts'] = $key + 1;
                RepairstoreGoodsImgRepository::add_one($imgArray);//存入图片信息
            }

            return hello_success('添加成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 编辑服务商品
     * yang 2019 10 30
     */
    public function edit_repair_goods(array $data)
    {
        try {
            $check = self::data_validation($data);
            if ($check['state'] == 1) {
                return $check;
            }
            $goods_id = $data['goods']['id'];
            if (empty($goods_id)) {
                return hello_error('服务商品id不能为空');
            }

            if (RepairstoreGoodsRepository::edit_one(hi_array_del_null($data['goods']))) {

                //删除原有数据
                RepairstoreGoodsImgRepository::delete_by_where(['goods_id' => $goods_id], true);
                $ad_data = array();
                $time = date('Y-m-d H:i:s');
                foreach (hi_array_del_null($data['pic']) as $key => $value) {
                    $ad_data[$key]['goods_id'] = $goods_id;
                    $ad_data[$key]['picurl'] = $value;
                    $ad_data[$key]['sorts'] = $key + 1;
                    $ad_data[$key]['created_at'] = $time;
                    $ad_data[$key]['updated_at'] = $time;
                }

                RepairstoreGoodsImgRepository::add_many($ad_data);//存入图片信息

            } else {
                return hello_error('编辑失败');
            }

            return hello_success('编辑成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取服务商品详情
     */
    public function get_repair_goods_info(int $nId)
    {
        try {
            if (empty($nId)) {
                return hello_error('参数不能为空');
            }
            //获取商品的主表信息
            $arr_option['field'] = ['id', 'name', 'type', 'price', 'price_indication', 'status', 'detail', 'fuwu'];
            $res = RepairstoreGoodsRepository::get_one((int)$nId, (array)$arr_option)->toArray();

            return hello_success('ok', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 服务商品上下架
     * 2019 10 31
     */
    public function change_repair_status(array $data)
    {
        try {

            $goods = hi_array_del_null($data['goods_id']);
            if (empty($goods)) {
                return hello_error('商品id不能为空');
            }
            foreach ($goods as $val) {
                RepairstoreGoodsRepository::change_one_state((int)$val, (int)$data['status']);
            }

            return hello_success('设置成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除指定服务商品
     * 2019 10 31
     */
    public function del_repair_goods(array $data)
    {
        try {
            $id_array = hi_array_del_null($data['id']);

            if (empty($id_array)) {
                return hello_error('商品id不能为空');
            }

            RepairstoreGoodsRepository::delete_more($id_array);

            return hello_success('删除成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     *  获取指定商品的评论信息
     *  hinq 2020 4 15
     *
     **/
    public function users_apprise_detail(array $arr_input)
    {
        try {
            $arr_where = ['type' => $arr_input['type'], 'user_id' => $arr_input['user_id'], 'order_id' => $arr_input['order_id'], 'goods_id' => $arr_input['goods_id']];
            $arr_option['field'] = ['score', 'id', 'content', 'images'];
            $arr_list = UsersAppriseRepository::get_one_by_where((array)$arr_where, (array)$arr_option);
            if (empty($arr_list->first())) {
                return hello_success('ok', null);
            }
            $images = [];
            if (!empty($arr_list['images'])) {
                $images = explode(',', $arr_list['images']);
                foreach ($images as &$item) {
                    $item = oss_full_url($item);
                }
            }
            $arr_list['images'] = $images;
            return hello_success('ok', $arr_list);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

}